<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>邮箱注册</h2>
      </div>
      <div class="auth-body">
        <el-form :model="form" :rules="rules" ref="registerForm" label-width="80px">
          <!-- 学号输入项 -->
          <el-form-item prop="userid" label="学号">
            <el-input
                v-model="form.userid"
                placeholder="请输入4-20位学号"
                class="auth-input"
            ></el-input>
          </el-form-item>

          <!-- 用户名输入项 -->
          <el-form-item prop="username" label="用户名">
            <el-input
                v-model="form.username"
                placeholder="请输入4-20位用户名"
                class="auth-input"
            ></el-input>
          </el-form-item>

          <el-form-item prop="email" label="邮箱">
            <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                class="auth-input"
            ></el-input>
          </el-form-item>

          <el-form-item prop="password" label="密码">
            <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入8-20位密码"
                show-password
                class="auth-input"
            ></el-input>
          </el-form-item>

          <el-form-item prop="realName" label="真实姓名">
            <el-input
                v-model="form.realName"
                placeholder="请输入真实姓名(可选)"
                class="auth-input"
            ></el-input>
          </el-form-item>

          <el-form-item prop="phone" label="手机号">
            <el-input
                v-model="form.phone"
                placeholder="请输入手机号(可选)"
                class="auth-input"
            ></el-input>
          </el-form-item>

          <el-form-item prop="code" label="验证码">
            <div class="code-input">
              <el-input
                  v-model="form.code"
                  placeholder="请输入验证码"
                  class="auth-input"
              ></el-input>
              <el-button
                  class="send-code-btn"
                  :disabled="countdown > 0"
                  @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item class="button-item">
            <el-button
                type="primary"
                class="auth-button"
                @click="handleRegister"
                :loading="loading"
            >注册</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="auth-footer">
        <span>已有账号? </span>
        <router-link to="/login" class="auth-link">立即登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from 'axios';
import {useStore} from "vuex";

const router = useRouter();
const registerForm = ref(null);
const loading = ref(false);
const countdown = ref(0);

const form = ref({
  userid: "",
  username: "",
  email: "",
  password: "",
  realName: "",
  phone: "",
  code: ""
});

// 验证规则保持不变...
const validateUserId = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入学号'));
  } else if (value.length < 4 || value.length > 20) {
    callback(new Error('学号长度必须在4-20个字符之间'));
  } else {
    callback();
  }
};

const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'));
  } else if (value.length < 4 || value.length > 20) {
    callback(new Error('用户名长度必须在4-20个字符之间'));
  } else {
    callback();
  }
};

const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'));
  } else if (value.length < 8 || value.length > 20) {
    callback(new Error('密码长度必须在8-20个字符之间'));
  } else {
    callback();
  }
};

const validatePhone = (rule, value, callback) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('手机号格式不正确'));
  } else {
    callback();
  }
};

const rules = {
  userid: [
    { validator: validateUserId, trigger: 'blur' }
  ],
  username: [
    { validator: validateUsername, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  realName: [
    { max: 50, message: '真实姓名长度不能超过50个字符', trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
};

const sendVerificationCode = async () => {
  try {
    await registerForm.value.validateField(['email']);

    const response = await axios.post('/user/email/register', {
      email: form.value.email
    });
    if (response.data.status === 200) {
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
      ElMessage.success('验证码已发送至您的邮箱');
    } else {
      ElMessage.error(response.data.msg || '验证码发送失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '验证码发送失败');
  }
};

const handleRegister = async () => {
  try {
    await registerForm.value.validate();
    loading.value = true;

    const registerData = {
      userid: form.value.userid,
      username: form.value.username,
      email: form.value.email,
      password: form.value.password,
      realName: form.value.realName,
      phone: form.value.phone,
      code: form.value.code
    };

    const response = await axios.post('/user/signup', registerData);

    if (response.data.status === 200) {
      ElMessage.success('注册成功');
      localStorage.setItem('token', response.data.data.JWT);
      localStorage.setItem('userInfo', JSON.stringify({
        userId: response.data.data.userId,
        username: response.data.data.username,
        role: response.data.data.role
      }));
      router.push('/');
    } else {
      ElMessage.error(response.data.msg || '注册失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '注册失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 70vh;
  background-color: #f5f5f5;
  padding: 20px;
  overflow: hidden;
  box-sizing: border-box;
}

.auth-card {
  width: 100%;
  max-width: 450px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 32px;
  margin: 0 auto;
}

/* 表单标签样式 */
.el-form-item__label {
  color: #606266;
  font-weight: 500;
  text-align: right;
  padding-right: 12px;
}

/* 输入框样式 */
.auth-input {
  width: 90%;
}

/* 验证码输入框布局 */
.code-input {
  display: flex;
  gap: 10px;
}

.send-code-btn {
  width: 120px;
  flex-shrink: 0;
}

/* 按钮样式 */
.button-item .el-form-item__content {
  justify-content: center !important;
  margin-left: 0 !important;
}

.auth-button {
  width: 80%;
  height: 40px;
  font-size: 16px;
}

/* 页眉样式 */
.auth-header {
  text-align: center;
  margin-bottom: 24px;
}

.auth-header h2 {
  color: #262626;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

/* 页脚样式 */
.auth-footer {
  text-align: center;
  margin-top: 16px;
  color: #8c8c8c;
  font-size: 14px;
}

.auth-link {
  color: #1890ff;
  text-decoration: none;
}

.auth-link:hover {
  text-decoration: underline;
}
</style>